const dbConfig = require("./dbConfig");
const mysql2 = require("mysql2");

// 默认升序 从小到大 ORDER BY monthTime ASC -> DESC 降序
async function getResult(sql, paramsList) {
  const promisePool = mysql2.createPool(dbConfig).promise();
  const result = await promisePool.query(sql, paramsList);

  return result;
}

// common base get
async function getList(database, paramsProp = [], paramsList = []) {
  return new Promise(async (resolve) => {
    let conditions = paramsProp.map((prop) => `${prop}=?`).join(" AND ");
    let sql = `SELECT * FROM ${database}`;
    sql = conditions ? (sql += ` WHERE ${conditions}`) : sql;
    console.log(sql);
    let res = await getResult({
      sql,
      paramsList,
    });
    console.log(sql, "===");
    resolve(res[0]);
  });
}

// common base update
async function updateList(
  database,
  updatePropList,
  updateValueList,
  searchValue,
  searchParam = "id"
) {
  return new Promise(async (resolve) => {
    getList(database, [searchParam], [searchValue]).then(async (res) => {
      if (res && res.length !== 0) {
        let sql = `UPDATE ${database} SET `;
        let updateStrings = updatePropList.map((prop) => `${prop}=?`).join(",");
        sql += updateStrings;
        sql += ` WHERE ${searchParam}=?`;
        let paramsList = [...updateValueList, searchValue];
        console.log(sql, "===");
        await getResult({
          sql,
          paramsList,
        });
        resolve();
      }
    });
  });
}

// common base delete
function deleteList(database, params, paramsProp = "id") {
  return new Promise(async (resolve) => {
    await getResult({
      sql: `DELETE FROM ${database} WHERE ${paramsProp}=?`,
      paramsList: [params],
    });
    resolve();
  });
}

module.exports = {
  getResult,
  getList,
  updateList,
  deleteList,
};
